package com.ma.chapter6.cas;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName AccountTest
 * @Author: mayongqiang
 * @DATE 2022/3/18 20:34
 * @Description: 第六章、共享模型之无锁  CAS
 */


public class AccountTest {
    public static void main(String[] args) {
        Account.demo(new AccountUnsafe(10000));
        Account.demo(new AccountSafe(10000));
    }
}

/* 无锁实现安全*/
class AccountSafe implements Account {

    //原子整数
    private AtomicInteger balance;

    public AccountSafe(int balance) {
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    @Override
    public void withdraw(Integer amount) {

        balance.getAndAdd(-1*amount);


        //while (true) {
        //    // 获取余额的最新值
        //    int prev = balance.get();
        //    //要修改的余额
        //    int next = prev - amount;
        //    // 真正去修改 CAS  比较并设置值
        //    /*
        //    在set之前，先比较prev与当前值
        //    - 不一致了 next作废 返回false 表示失败
        //     比如，别的线程已经做了剑法，当前值已经被减到990
        //        那么本线程的990就作废了，进入while下次循环重试
        //    - 一致，以next设置为新值，返回true表示成功
        //    * */
        //    if (balance.compareAndSet(prev, next)) {
        //        break;
        //    }
        //}
    }
}


/* synchronized加锁实现安全 */
class AccountUnsafe implements Account {
    private Integer balance;

    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }

    @Override
    public synchronized Integer getBalance() {
        return balance;
    }

    @Override
    public synchronized void withdraw(Integer amount) {
        balance -= amount;
    }
}

interface Account {
    // 获取余额

    Integer getBalance();
    // 取款

    void withdraw(Integer amount);

    /**
     * 方法内会启动 1000 个线程，每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        long start = System.nanoTime();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(account.getBalance()
                + " cost: " + (end - start) / 1000_000 + " ms");
    }

}

